from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db

import os
import markdown

from util import *

class BlogEntry(db.Model):
    headline = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    body = db.TextProperty()

    def bodyAsMarkdown(self):
        return markdown.markdown(self.body)

def loadEntry(entryId):
    key = db.Key.from_path('BlogEntry', long(entryId))
    entry = db.get(key)
    return entry

class ShowBlog(webapp.RequestHandler):
    def get(self):

        pagePath = []
        posts = []
        if self.request.get('id'):
            entry = loadEntry(self.request.get('id'))
            posts.append(entry)
            pagePath.append(PageDir("blog", "/blog"))
            pagePath.append(PageDir(posts[0].headline, ""))
        else:
            posts = db.GqlQuery("SELECT * FROM BlogEntry ORDER BY date DESC LIMIT 3")
            pagePath.append(PageDir("blog", ""))
            
        template_values = {
            'path': pagePath,
            'fgColor': "\"#FFFFFF\"",
            'posts': posts,
            'user': MyUser()
        }

        path = os.path.join(os.path.dirname(__file__), 'blog.html')
        self.response.out.write(template.render(path, template_values))

class EditBlog(webapp.RequestHandler):
    def get(self):
        if self.request.get('id'):
            entry = loadEntry(self.request.get('id'))
        else:
            entry = BlogEntry()
            entry.headline = ""
            entry.body = ""
            entry.put()
            
        pagePath = []
        pagePath.append(PageDir("blog", "blog"))
        pagePath.append(PageDir(entry.headline + ": EDIT", ""))

        template_values = {
            'entry': entry,
            'path': pagePath,
            'fgColor': "\"#FFFFFF\"",
            'user': MyUser()
        }
        path = os.path.join(os.path.dirname(__file__), 'editBlog.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        myUser = MyUser()
        if not myUser.canEdit:
            self.redirect("/blog")

        entry = loadEntry(self.request.get('myid').strip())
        headline = self.request.get('headline').strip()
        if headline:
            entry.headline = self.request.get('headline').strip()
            entry.body = self.request.get('body').strip()
            key = entry.put()
        else:
            entry.delete()
        self.redirect("/blog?id="+str(entry.key().id()))
